package com.mo.lib.adapter

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import com.mo.lib.ui.action.HandlerAction

/**
 * @ author：mo
 * @ data：2019/4/4：10:22
 * @ 功能：FragmentPagerAdapter 适配器 适用于较少的碎片切换，可变换tab提示
 * KFragmentPagerAdapter myAdapter = new KFragmentPagerAdapter(getSupportFragmentManager(), mFragments, mTitleList);
 * vp_history.setAdapter(myAdapter);
 */
class KFragmentPagerAdapter : FragmentPagerAdapter, HandlerAction {
    private var mFragments: MutableList<Fragment>? = null
    private var mTitleList: List<String>? = null

    constructor(fm: FragmentManager?) : super(fm!!) {}
    constructor(fm: FragmentManager?, mFragments: MutableList<Fragment>?) : super(fm!!) {
        this.mFragments = mFragments
    }

    constructor(fm: FragmentManager?, mFragments: MutableList<Fragment>?, mTitleList: List<String>?) : super(fm!!) {
        this.mFragments = mFragments
        this.mTitleList = mTitleList
    }

    constructor(activity: FragmentActivity, mFragments: MutableList<Fragment>?, mTitleList: List<String>?) : super(activity.supportFragmentManager) {
        this.mFragments = mFragments
        this.mTitleList = mTitleList
    }

    override fun getItem(position: Int): Fragment {
        return mFragments!![position]
    }

    override fun getItemId(position: Int): Long {
        // 获取当前数据的hashCode
        val hashCode = mFragments!![position].hashCode()
        return hashCode.toLong()
    }

    override fun getCount(): Int {
        return mFragments!!.size
    }

    fun addFragment(fragment: Fragment, index: Int) {
        mFragments!!.add(fragment)
        notifyDataSetChanged()
    }

    fun remove(index: Int) {
        mFragments!!.removeAt(index)
        notifyDataSetChanged()
    }

    fun setmTitleList(mTitleList: List<String>?) {
        this.mTitleList = mTitleList
        post { notifyDataSetChanged() }
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return if (mTitleList != null) {
            mTitleList!![position]
        } else ""
    }
}